/*
  Created by 1271107612@qq.com.
  User: DELL
  Date: 2022/4/11
  Time: 13:48
  DESCRIPTION: 
*/
package com.zzy.face.controller;

import com.zzy.face.dto.StudentInfo;
import com.zzy.face.dto.TeacherInfo;
import com.zzy.face.model.Account;
import com.zzy.face.model.Student;
import com.zzy.face.service.AccountService;
import com.zzy.face.service.StudentService;
import com.zzy.face.utils.Result;
import com.zzy.face.utils.ResultCode;
import com.zzy.face.utils.jwt.Jwt;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/student")
public class StudentController {
    final Jwt jwt;
    final StudentService studentService;
    final AccountService accountService;
    public StudentController(Jwt jwt, StudentService studentService, AccountService accountService) {
        this.jwt = jwt;
        this.studentService = studentService;
        this.accountService = accountService;
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ApiOperation(value = "获取个人信息", notes = "获取个人信息")
    public Result info(HttpServletRequest request) {
        try {
            StudentInfo studentInfo = studentService.findStudentInfo(jwt.getId(request));
            return new Result(ResultCode.SUCCESS, studentInfo);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR, e);
        }
    }

    @RequestMapping(value = "/{uid}", method = RequestMethod.GET)
    @ApiOperation(value = "获取个人信息", notes = "获取个人信息")
    public Result info(@PathVariable("uid") Long uid) {
        try {
            StudentInfo studentInfo = studentService.findStudentInfo(uid);
            return new Result(ResultCode.SUCCESS, studentInfo);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR, e);
        }
    }

    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ApiOperation(value = "修改个人信息", notes = "修改个人信息")
    public Result changeInfo(@RequestBody StudentInfo form, HttpServletRequest request){
        int identity = Integer.parseInt(jwt.token(request).get("identity").toString());
        if ((identity>=accountService.findByMobile(form.getMobile()).getIdentity())){
            Account account = accountService.findByUid(form.getUid());
            Student student = studentService.findById(form.getUid());
            account.setMobile(form.getMobile());
            account.setName(form.getName());
            account.setSex(form.getSex());
            account.setState(form.getState());
            account.setCollege(form.getCollege());
            student.setMajor(form.getMajor());
            student.setUClass(form.getUClass());
            studentService.save(student);
            accountService.save(account);
            return new Result(ResultCode.SUCCESS);
        }
        return new Result(ResultCode.UN_AUTHORISE);
    }

}
